// 前端 i18n 客户端配置
class I18nClient {
    constructor() {
        this.currentLanguage = 'zh-CN';
        this.supportedLanguages = ['zh-CN', 'en-US', 'ja-JP', 'ko-KR', 'fr-FR', 'de-DE', 'es-ES', 'pt-BR', 'ru-RU', 'it-IT', 'nl-NL', 'pl-PL', 'tr-TR', 'vi-VN', 'th-TH', 'ar-SA', 'hi-IN'];
        this.translations = {};
        this.isInitialized = false;
    }

    // 初始化 i18n 客户端
    async init() {
        if (this.isInitialized) return;
        
        try {
            // 从 URL 参数、localStorage 或浏览器语言检测
            const urlParams = new URLSearchParams(window.location.search);
            const urlLang = urlParams.get('lang');
            const storedLang = localStorage.getItem('preferredLanguage');
            const browserLang = navigator.language || navigator.userLanguage;
            
            // 确定当前语言
            this.currentLanguage = urlLang || storedLang || this.detectBrowserLanguage(browserLang) || 'zh-CN';
            
            // 加载翻译文件
            await this.loadTranslations(this.currentLanguage);
            
            // 更新页面语言属性
            document.documentElement.lang = this.currentLanguage;
            
            // 应用翻译
            this.applyTranslations();
            
            // 保存语言偏好
            localStorage.setItem('preferredLanguage', this.currentLanguage);
            
            this.isInitialized = true;
            console.log('I18nClient initialized with language:', this.currentLanguage);
            
            // 监听语言切换事件
            this.setupEventListeners();
            
        } catch (error) {
            console.error('Failed to initialize I18nClient:', error);
        }
    }

    // 检测浏览器语言
    detectBrowserLanguage(browserLang) {
        if (!browserLang) return null;
        
        // 简化语言代码匹配
        const langMap = {
            'zh': 'zh-CN',
            'en': 'en-US', 
            'ja': 'ja-JP',
            'ko': 'ko-KR'
        };
        
        const primaryLang = browserLang.split('-')[0];
        return langMap[primaryLang] || null;
    }

    // 加载翻译文件
    async loadTranslations(language) {
        try {
            const response = await fetch(`/api/i18n/translations/${language}`);
            if (response.ok) {
                this.translations[language] = await response.json();
            } else {
                console.warn(`Translation file for ${language} not found, using fallback`);
                // 如果目标语言文件不存在，尝试加载默认语言
                if (language !== 'zh-CN') {
                    await this.loadTranslations('zh-CN');
                }
            }
        } catch (error) {
            console.error('Failed to load translations:', error);
        }
    }

    // 应用翻译到页面
    applyTranslations() {
        const translations = this.translations[this.currentLanguage] || {};
        
        // 翻译所有带有 data-i18n 属性的元素
        document.querySelectorAll('[data-i18n]').forEach(element => {
            const key = element.getAttribute('data-i18n');
            const translation = translations[key];
            if (translation) {
                if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {
                    element.placeholder = translation;
                } else if (element.tagName === 'IMG') {
                    element.alt = translation;
                } else {
                    element.textContent = translation;
                }
            }
        });

        // 翻译所有带有 data-i18n-title 属性的元素
        document.querySelectorAll('[data-i18n-title]').forEach(element => {
            const key = element.getAttribute('data-i18n-title');
            const translation = translations[key];
            if (translation) {
                element.title = translation;
            }
        });

        // 翻译页面标题
        const pageTitle = translations['page.title'];
        if (pageTitle) {
            document.title = pageTitle;
        }
    }

    // 切换语言
    async switchLanguage(language) {
        if (!this.supportedLanguages.includes(language)) {
            console.error('Unsupported language:', language);
            return;
        }

        this.currentLanguage = language;
        localStorage.setItem('preferredLanguage', language);
        
        // 加载新语言的翻译
        await this.loadTranslations(language);
        
        // 更新页面语言属性
        document.documentElement.lang = language;
        
        // 应用翻译
        this.applyTranslations();
        
        // 触发语言切换事件
        this.dispatchLanguageChangeEvent(language);
        
        console.log('Language switched to:', language);
    }

    // 设置事件监听器
    setupEventListeners() {
        // 监听语言切换按钮点击
        document.addEventListener('click', (e) => {
            if (e.target.matches('[data-switch-lang]')) {
                const language = e.target.getAttribute('data-switch-lang');
                this.switchLanguage(language);
            }
        });
    }

    // 分发语言切换事件
    dispatchLanguageChangeEvent(language) {
        const event = new CustomEvent('languageChanged', {
            detail: { language }
        });
        document.dispatchEvent(event);
    }

    // 获取翻译文本
    t(key, defaultValue = '') {
        const translations = this.translations[this.currentLanguage] || {};
        return translations[key] || defaultValue || key;
    }

    // 获取当前语言
    getCurrentLanguage() {
        return this.currentLanguage;
    }

    // 获取支持的语言列表
    getSupportedLanguages() {
        return this.supportedLanguages;
    }
}

// 创建全局实例
window.i18nClient = new I18nClient();

// 自动初始化
document.addEventListener('DOMContentLoaded', () => {
    window.i18nClient.init();
});

export default I18nClient;